# interview\admin.py
import csv
import logging
from datetime import datetime
from django.contrib import admin, messages
from django.db.models import Q
from django.http import HttpResponse
from django.utils.safestring import mark_safe

from interview.models import Candidate
from interview import candidate_fieldset
from interview import dingtalk
from jobs.models import Resume

logger = logging.getLogger(__name__)
exportable_fields = ('username', 'city', 'phone', 'bachelor_school', 'master_school', 'degree', 'first_result',
                     'first_interviewer_user', 'second_result', 'second_interviewer_user', 'hr_result', 'hr_score',
                     'hr_remark', 'hr_interviewer_user')


def notify_interviewer(model_admin, request, queryset):
    candidates_list = []
    interviewers_list = []
    for obj in queryset:
        candidates_list.append(obj.username)
        interviewers_list.append(obj.first_interviewer_user.username)
    candidates_str = ', '.join(candidates_list)
    interviewers_str = ', '.join(interviewers_list)
    dingtalk.send(f"候选人{candidates_str}进入面试环节，面试官请做好面试准备：{interviewers_str}")
    messages.add_message(request, messages.INFO, f"已经成功发送面试通知。")


def export_model_as_csv(model_admin, request, queryset):
    response = HttpResponse(content_type='text/csv')
    field_list = exportable_fields
    response['Context-Disposition'] = 'attachment; filename=recruitment-candidates-list-%s.csv' % (
        datetime.now().strftime('%Y-%m-%d-%H-%M-%S'),)

    writer = csv.writer(response)
    writer.writerow(
        [queryset.model._meta.get_field(f).verbose_name.title() for f in field_list]
    )
    for obj in queryset:
        csv_line_values = []
        for field in field_list:
            field_obj = queryset.model._meta.get_field(field)
            field_value = field_obj.value_from_object(obj)
            csv_line_values.append(field_value)
        writer.writerow(csv_line_values)
    logger.info(f"{request.user} exported {len(queryset)} candidate records.")
    return response


export_model_as_csv.short_description = u'导出为CSV文件'
export_model_as_csv.allowed_permissions = ('export',)


# Register your models here.

class CandidateAdmin(admin.ModelAdmin):
    actions = [export_model_as_csv, notify_interviewer]

    # 判断当前用户是否有权限导出
    def has_export_permission(self, request):
        opts = self.opts
        strings = request.user.has_perm(f"{opts.app_label}.export")
        return strings

    exclude = ('creator', 'created_date', 'modified_date')
    list_display = (
        'username', 'city', 'bachelor_school', 'get_resume', 'first_score', 'first_result', 'first_interviewer_user',
        'second_result', 'second_interviewer_user', 'hr_score', 'hr_result', 'last_editor'
    )

    # 筛选
    list_filter = ('city', 'first_result', 'second_result', 'hr_result',
                   'first_interviewer_user', 'second_interviewer_user', 'hr_interviewer_user')
    # 搜索
    search_fields = ('username', 'phone', 'email', 'bachelor_school')
    # 默认排序
    ordering = ('hr_result', 'second_result', 'first_result')

    # 可编辑、只读
    default_list_editable = ('first_interviewer_user', 'second_interviewer_user')
    default_list_readonly = ('first_interviewer_user', 'second_interviewer_user')

    def get_list_editable(self, request):
        group_names = self.get_group_names(request.user)
        if request.user.is_superuser or 'hr' in group_names:
            return self.default_list_editable
        return ()

    def get_changelist_instance(self, request):
        self.list_editable = self.get_list_editable(request)
        return super(CandidateAdmin, self).get_changelist_instance(request)

    @staticmethod
    def get_group_names(user):
        group_names = []
        for g in user.groups.all():
            group_names.append(g.name)
        return group_names

    # 对于非管理员、非HR，获取自己是一面面试官或者二面面试官的候选人集合
    def get_queryset(self, request):
        qs = super(CandidateAdmin, self).get_queryset(request)

        group_names = self.get_group_names(request.user)
        if request.user.is_superuser or 'hr' in group_names:
            return qs
        else:  # 返回 Candidate 的子集
            s = Candidate.objects.filter(
                Q(first_interviewer_user=request.user) | Q(second_interviewer_user=request.user))
            return s

    def get_readonly_fields(self, request, obj=None):
        group_names = self.get_group_names(request.user)
        if 'interviewer' in group_names:
            logger.info(f"interview is in user's group for {request.user.username}")
            return self.default_list_readonly
        return ()

    # 一面面试官仅填写一面反馈，二面面试官可以填写二面反馈， hr拥有候选人的全部编辑权限
    def get_fieldsets(self, request, obj=None):
        group_names = self.get_group_names(request.user)
        if 'interviewer' in group_names and obj.first_interviewer_user == request.user:
            return candidate_fieldset.default_fieldsets_first
        if 'interviewer' in group_names and obj.second_interviewer_user == request.user:
            return candidate_fieldset.default_fieldsets_second
        return candidate_fieldset.default_fieldsets

    def get_resume(self, obj):
        if obj.phone:
            resumes = Resume.objects.filter(phone=obj.phone)
            if resumes and len(resumes) > 0:
                return mark_safe(f"<a href='/resume/{resumes[0].id}' target='_blank'>查看简历</a>")
        else:
            return ""

    get_resume.short_description = '查看简历'
    get_resume.allow_tags = True


admin.site.register(Candidate, CandidateAdmin)
